package com.mallcloud.mall.app.service.impl;

import com.google.common.collect.Lists;
import com.mallcloud.mall.app.api.entity.vo.AppCartItemVO;
import com.mallcloud.mall.app.api.entity.vo.AppCartWithAmountVO;
import com.mallcloud.mall.app.service.AppCartAdapterService;
import com.mallcloud.mall.common.core.exception.FailException;
import com.mallcloud.mall.product.api.entity.ShopDetailModel;
import com.mallcloud.mall.product.service.ShopDetailService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class AppCartAdapterServiceImpl implements AppCartAdapterService {
    private final ShopDetailService shopDetailService;

    @Override
    public List<AppCartWithAmountVO.AppShopCartVO> conversionShopCart(List<AppCartItemVO> cartItemList) {
        Map<Long, List<AppCartItemVO>> shopCartMap = cartItemList.stream().collect(Collectors.groupingBy(AppCartItemVO::getShopId));
        List<AppCartWithAmountVO.AppShopCartVO> shopCarts = Lists.newArrayList();

        List<ShopDetailModel> shopDetailList = shopDetailService.listByIds(shopCartMap.keySet());
        Map<Long, String> shopDetailMap = shopDetailList.stream().collect(Collectors.toMap(ShopDetailModel::getShopId, ShopDetailModel::getShopName, (m, n) -> m));
        for (Long shopId : shopCartMap.keySet()) {
            // 构建每个店铺的购物车信息
            AppCartWithAmountVO.AppShopCartVO shopCart = buildShopCart(shopId, shopCartMap.get(shopId));
            shopCart.setShopId(shopId);
            shopCart.setShopCartItem(shopCartMap.get(shopId));

            if (!shopDetailMap.containsKey(shopId)) {
                throw new FailException("查询店铺失败");
            }
            // 店铺信息
            shopCart.setShopName(shopDetailMap.get(shopId));
            shopCarts.add(shopCart);
        }
        return shopCarts;
    }

    /**
     * 构建每个店铺的购物车信息
     *
     * @param shopId
     * @param shopCartItems
     * @return
     */
    private AppCartWithAmountVO.AppShopCartVO buildShopCart(Long shopId, List<AppCartItemVO> shopCartItems) {
        AppCartWithAmountVO.AppShopCartVO shopCart = new AppCartWithAmountVO.AppShopCartVO();
        shopCart.setShopId(shopId);
        long total = 0L;
        int totalCount = 0;
        for (AppCartItemVO shopCartItem : shopCartItems) {
            total += shopCartItem.getTotalAmount();
            totalCount += shopCartItem.getCount();
        }
        shopCart.setTotal(total);
        shopCart.setTotalCount(totalCount);
        return shopCart;
    }
}
